package week2.blog_code.exer1002;

import java.util.Scanner;

public class Main {
    private static int reversePairCount = 0;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextInt()) {
            reversePairCount = 0;
            int n = scanner.nextInt();
            int[] arr = new int[n];
            for (int i = 0; i < n; i++) {
                arr[i] = scanner.nextInt();
            }
            partition(arr, 0, n - 1);
            System.out.println(reversePairCount);
        }
    }

    /**
     * 统计区间[left, right]内部逆序对的个数
     * @param arr 数组元素
     * @param left 左区间
     * @param right 右区间
     */
    private static void partition(int[] arr, int left, int right) {
        if (left >= right) {
            return;
        }
        // 计算中心下标
        int mid = (left + right) / 2;
        partition(arr, left, mid); // 统计左区间逆序对个数并排序
        partition(arr, mid + 1, right); // 统计右区间逆序对个数并排序
        int[] tmp = new int[right - left + 1]; // 临时数组
        int tmpIndex = 0;
        int left1 = left;
        int right1 = mid;
        int left2 = mid + 1;
        int right2 = right;
        while (left1 <= right1 && left2 <= right2) {
            if (arr[left1] > arr[left2]) {
                tmp[tmpIndex++] = arr[left1];
                left1++;
                reversePairCount += (right2 - left2 + 1);
            } else {
                tmp[tmpIndex++] = arr[left2];
                left2++;
            }
        }
        while (left1 <= right1) {
            tmp[tmpIndex++] = arr[left1];
            left1++;
        }
        while (left2 <= right2) {
            tmp[tmpIndex++] = arr[left2];
            left2++;
        }
        // 拷贝回原数组
        for (int i = 0; i < tmpIndex; i++) {
            arr[left + i] = tmp[i];
        }
    }
}
